package com.hw.hcit.conf;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.hw.hcit.R;

import android.app.ActivityManager;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;


public class JTestItem extends Fragment {
    private String TAG="JTestItem";

    //JTestItemCallback cb = null;

    //    public JTestItem(JTestItemCallback callback) {
//        cb = callback;
//    }
    private String path = "persist/mmi_result.txt";

    JCtrlCallback cb = null;
    String name = "";
    Toast mToast, pToast;

    public JTestItem(JCtrlCallback cb) {
        this.cb = cb;
    }

    public JTestItem() {

    }

    /* (non-Javadoc)
     * @see android.app.Fragment#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        /*gaoshenpan 15-11-21 fix when QcnvItems dispose IntentReceiver not register begin*/
        if (!isMonkeyRunning()) {
        }
        /*gaoshenpan 15-11-21 fix when QcnvItems dispose IntentReceiver not register end*/
    }
    
    /* (non-Javadoc)
     * @see android.app.Fragment#onResume()
     */

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        /*
         * gaoshenpan 15-11-21 fix when QcnvItems dispose IntentReceiver not
         * register begin
         */
        if (isMonkeyRunning()) {
            Log.d("mmI", "---m---is----->onResume()");
            Config.GetActivity().finish();
        } else {

        }
        /*
         * gaoshenpan 15-11-21 fix when QcnvItems dispose IntentReceiver not
         * register end
         */
        /* 15-11-12 gaoshenpan fix judge isMonkeyRuning when onResume begin */

    }

    public static boolean isMonkeyRunning() {
        return ActivityManager.isUserAMonkey();
    }

    /*15-11-12 gaoshenpan fix judge isMonkeyRuning when onResume end*/
    /* (non-Javadoc)
     * @see android.app.Fragment#onDestroy()
     */
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.d("hh", "onDestroy--1-->");
    }



    public boolean rewriteOneByteOfNv2499(int idx, char testResult) {
        byte[] bresult = null;
        String key = String.valueOf(idx);
        String value = String.valueOf(testResult);
        Log.v(TAG, "key:" + key + " value:" + value);
        String str = readfile(path);
        Log.v(TAG,"str="+str);
        char[] strChar = str.toCharArray();
        Log.v(TAG," strChar="+strChar);
        strChar[idx]= testResult;
        Log.v(TAG," strChar="+strChar);
        String out = String.valueOf(strChar);
        writefile(path, out);
        boolean result = !TextUtils.isEmpty(out);
        return result;
    }

    private String readfile(String filePath) {
        StringBuilder txtContent = new StringBuilder();
        byte[] b = new byte[1];
        InputStream in = null;
        try {
            in = new FileInputStream(filePath);
            while (in.read(b) != -1) {
                String s  = new String(b);
                txtContent.append(s);
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return txtContent.toString();
    }

    private void writefile(String path, String in) {
        try {
            FileOutputStream outStream = new FileOutputStream(path);
            OutputStreamWriter writer = new OutputStreamWriter(outStream, "gb2312");
            Log.v(TAG, " in=" + in);
            writer.write(in);
            writer.flush();
            writer.close();
            outStream.close();
        } catch (IOException e) {
            Log.v(TAG, " e=" + e);
            e.printStackTrace();
        }

    }

    /* 15-10-24 gaoshenpan fix add method to tell if NVSaved begin */
    public boolean rewriteOneByteOfNv2499_1(int idx, char testResult) {
        byte[] bresult = null;
        String key = String.valueOf(idx);
        String value = String.valueOf(testResult);
        Log.v(TAG, "key:" + key + " value:" + value);
        String str = readfile(path);
        Log.v(TAG,"str="+str);
        char[] strChar = str.toCharArray();
        Log.v(TAG," strChar="+strChar);
        strChar[idx]= testResult;
        Log.v(TAG," strChar="+strChar);
        String out = String.valueOf(strChar);
        writefile(path, out);
        boolean result = !TextUtils.isEmpty(out);
        return result;
    }

    /* 15-10-24 gaoshenpan fix add method to tell if NVSaved end */
    public void testFinish(boolean b) {
        testFinish(b, 1, false);
    }

    public void testFinish(boolean b, int step, boolean onlyMove) {
        if (cb != null) {
            cb.action(b, step, onlyMove);
        } else {
            Config.cb.action(b, step, onlyMove);
        }
    }

    public List<String> getData() {
        return null;
    }

    public boolean getResult() {
        return false;
    }

    public String getResultInfo() {
        return null;
    }

    public void startTest() {

    }

    public void stopTest() {
    }

    public void refresh() {

    }

    public void setName(String s) {
        name = s;
    }

    public String getName() {
        return name;
    }

    public void dissmissPowerClicked() {
        if (pToast != null) {
            pToast.cancel();
        }
    }

    public void showBatteryTooLow() {
        if (Config.GetActivity() != null) {
            TextView textView = new TextView(Config.GetActivity());
            textView.setText(R.string.battery_too_low);
            textView.setTextColor(Color.RED);
            if (mToast != null) {
                mToast.cancel();
            }
            mToast = new Toast(Config.GetActivity());
            mToast.setView(textView);
            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.show();
        }
    }

    public void showPowerClicked() {
        if (Config.GetActivity() != null) {
            View view = View.inflate(Config.GetActivity(), R.layout.my_toast, null);
            if (mToast != null) {
                mToast.cancel();
            }
            if (pToast != null) {
                pToast.cancel();
            }

            pToast = new Toast(Config.GetActivity());
            pToast.setView(view);
            pToast.setGravity(Gravity.CENTER, 0, 0);
            pToast.setDuration(Toast.LENGTH_SHORT);
            pToast.show();
        }
    }

    public void showTestUncomplete() {
        if (Config.GetActivity() != null) {
            TextView textView = new TextView(Config.GetActivity());
            textView.setText(R.string.toast_test_uncomplete);
            textView.setTextColor(Color.RED);
            if (mToast != null) {
                mToast.cancel();
            }
            mToast = new Toast(Config.GetActivity());
            mToast.setView(textView);
            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.show();
        }
    }

    public void showSDCardTestFail() {
        if (Config.GetActivity() != null) {
            TextView textView = new TextView(Config.GetActivity());
            textView.setText(R.string.sdcard_test_fail_toast);
            textView.setTextColor(Color.RED);
            if (mToast != null) {
                mToast.cancel();
            }
            mToast = new Toast(Config.GetActivity());
            mToast.setView(textView);
            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.show();
        }
    }

    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
            dissmissPowerClicked();
            testFinish(true, 1, true);
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
            dissmissPowerClicked();
            testFinish(true, -1, true);
        }
        return true;
    }

    public void onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        /* 15-11-12 gaoshenpan fix judge isMonkeyRuning when Touched begin */
        if (isMonkeyRunning()) {
            Log.d("mmI", "---mother---is----->onTouchEvent()");
            Config.GetActivity().finish();
        }
        /* 15-11-12 gaoshenpan fix judge isMonkeyRuning when Touched end */
    }
}